<?php

class Organization extends ElggObject
{
	//Constants
	protected $managerRelationId = 'org_admin';
	protected $tournamentRelationId = 'tournament';
	
	//Protected Arrays 
	protected $managers;
	protected $tournaments;
	
	protected function initializeAttributes()
	{
		parent::initializeAttributes();
		$this -> attributes['subtype'] = 'organization';
	}
	
	/**
	 * Check the user is an admin or this organization's manager
	 * @param ElggUser $user The user to check (Logged user by default)
	 * @return bool
	 */
	public function isManager($user = null)
	{
		if(!$user) $user = elgg_get_logged_in_user_entity();
		if($user->isAdmin()) return true;
		
		
		$managers = $this->getManagers();
		foreach($managers as $manager)
		{
			if($manager->guid == $user->guid)
				return true;
		}
		
		return false;
	}
	/**
	 * Return an array of users who have permissions to edit this organization
	 * @return array
	 */
	public function getManagers()
	{
		if(!$this->managers)
			$this->managers = parent::getEntitiesFromRelationship($this->managerRelationId);
		return $this->managers;
	}
	/**
	 * Add a relationship of manager
	 * @param int $guid
	 * @return bool
	 */
	public function addManager($guid)
	{
		$user = get_entity($guid);
		
		if($this->isManager() && elgg_instanceof($user, 'user') && !$this->isManager($user))
			return parent::addRelationship($user,$this->managerRelationId);
		else
			return false;
	}
	/**
	 * Add relationships of managers
	 * @param array $users 
	 * @return int
	 */
	public function addManagers($users)
	{
		$count = 0;
		foreach($users as $user)
		{
			if($this->addManager($user))
				$count++;
		}
		return $count;
	}
	/**
	 * Remove a relationship of manager
	 * @param ElggUser $user
	 * @return bool
	 */
	public function removeManager($user)
	{
		return parent::removeRelationship($user,$this->managerRelationId);
	}

	/**
	 * Return a list of tournaments
	 * @return array
	 */
	public function getTournaments()
	{
		if(!$this->tournaments)
			$this->tournaments = parent::getEntitiesFromRelationship($this->tournamentRelationId);
		return $this->tournaments;
	}
	
	/**
	 * Attach a tournament to the organization
	 * @param Tournament $tournament
	 * @return bool
	 */
	public function addTournament($tournament)
	{
		if($this->isManager())
		{
			return $this->addRelationship($tournament->guid,$this->tournamentRelationId);
		}
		return false;
	}
}